package com.soilflow.info.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.soilflow.common.annotation.DataScope;
import com.soilflow.common.domain.LandAuction;
import com.soilflow.common.domain.LandAuctionEnroll;
import com.soilflow.common.domain.dto.LandAuctionEnrollDto;
import com.soilflow.common.domain.vo.LandAuctionEnrollVo;
import com.soilflow.common.exception.ServiceException;
import com.soilflow.common.utils.SecurityUtils;
import com.soilflow.info.mapper.LandAuctionEnrollMapper;
import com.soilflow.info.service.LandAuctionEnrollService;
import com.soilflow.info.service.LandAuctionService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class LandAuctionEnrollServiceImpl extends ServiceImpl<LandAuctionEnrollMapper, LandAuctionEnroll> implements LandAuctionEnrollService {
    @Resource
    private LandAuctionEnrollMapper landAuctionEnrollMapper;
    @Resource
    private LandAuctionService landAuctionService;

    @DataScope(deptAlias = "li")
    @Override
    public List<LandAuctionEnrollVo> auctionEnrollInfoList(LandAuctionEnrollDto dto) {
      return landAuctionEnrollMapper.auctionEnrollInfoList(dto);
    }
    @Override
    public List<LandAuctionEnrollVo> myAuctionEnrollInfoList(LandAuctionEnrollDto dto) {
        return landAuctionEnrollMapper.myAuctionEnrollInfoList(dto);
    }
    @Override
    public Boolean AddAuctionEnrollInfo(LandAuctionEnrollDto dto) {
        dto.setEnrollTime(new Date());
        //校验是否参加过竞拍
        LambdaQueryWrapper<LandAuctionEnroll> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dto.getAuctionId() !=null,LandAuctionEnroll::getAuctionId,dto.getAuctionId())
                .eq(LandAuctionEnroll::getUserId,SecurityUtils.getUserId()).last("limit 1");
        if (!ObjectUtils.isEmpty(landAuctionEnrollMapper.selectOne(queryWrapper))){
            return false;
        }
        //dto.getAuctionId()
        LandAuction landAuction = landAuctionService.getById(dto.getAuctionId());
        if (!landAuction.getStatus().equals("1") ){
            throw new ServiceException("该竞拍暂不能报名！");
        }
        //添加竞拍
        LandAuctionEnroll landAuctionEnroll = new LandAuctionEnroll();
        landAuctionEnroll.setUserId(SecurityUtils.getUserId());
        landAuctionEnroll.setAuctionId(dto.getAuctionId());
        landAuctionEnroll.setEnrollTime(dto.getEnrollTime());
        landAuctionEnroll.setInfoId(dto.getInfoId());
        landAuctionEnrollMapper.insert(landAuctionEnroll);
        return true;
    }
}
